package org.mogu;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.UrlSync;
import org.mogu.tools.UserUtil;
import org.mogu.R;

import com.mobclick.android.MobclickAgent;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TMain extends Activity {
	Button login;
	Button reset;
	EditText username;
	EditText password;
//	EditText repassword;
//	CheckBox cpassword;
//	LinearLayout repd;
	LinearLayout reg;
	LinearLayout loginform;
	LinearLayout ckform;

	ActiveUserHelper auh;
	
	TextView msg;
	
	Context context;
	String uname;

	List<NameValuePair> params = null;
	DefaultHttpClient client;
	HttpResponse httpResponse;
	public ProgressDialog myDialog = null;
	
	private Handler mMainHandler;
	
//	Runnable r;
//	Handler h;

	/* Post运作传送变数必须用NameValuePair[]阵列储存 */
	// params=new ArrayList<NameValuePair>();
	// params.add(new BasicNameValuePair("username","beijibear"));
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context=this;
//		h=new Handler();
		File dirFile = new File(Convert.infPath);   
        if(!dirFile.exists())
        {
            dirFile.mkdir();
        } 
        dirFile=new File(Convert.picPath);
        if(!dirFile.exists())
        {
            dirFile.mkdir();
        } 
        
		
		setContentView(R.layout.login);
		client = new DefaultHttpClient();

		login = (Button) findViewById(R.id.ok);
		reset = (Button) findViewById(R.id.cancel);
		username = (EditText) findViewById(R.id.uname);
		password = (EditText) findViewById(R.id.password);
//		repassword = (EditText) findViewById(R.id.repassword);
//		cpassword = (CheckBox) findViewById(R.id.writeme);
//		repd = (LinearLayout) findViewById(R.id.repd);
		reg = (LinearLayout) findViewById(R.id.reg);
		
		msg=(TextView)findViewById(R.id.msg);
//		repd.setVisibility(View.GONE);
		reg.setVisibility(View.GONE);
		loginform = (LinearLayout) findViewById(R.id.login);
		ckform = (LinearLayout) findViewById(R.id.ckform);
		// 检测是否记录密码了
		auh = DBhelper.getDBHelper(this);

		mMainHandler = new Handler() {
			 
            @Override
            public void handleMessage(Message msg) {
//                Log.i(TAG, "Got an incoming message from the child thread - "
//                        + (String) msg.obj);
            	if(msg.obj.toString().indexOf("reg")==0){
            		String u=msg.obj.toString().substring(3);
            		username.setText(u);
            		return;
            	}
//            	if(msg.obj.toString().indexOf("login")==0){
////            		String u=msg.obj.toString().substring(5);
////            		username.setText(u);
////					password.setText(u);
//					onLogin(null);
//					return;
//            	}
            	
            		// 接收子线程的消息
                	Toast.makeText(context, msg.obj.toString(), 4000).show();
            	
                
//                info.setText((String) msg.obj);
            }
 
        };
        synchronized (InfoSync.class) {
        SQLiteDatabase readdb = auh.getReadableDatabase();
        Cursor activelist = readdb
				.rawQuery(
						"select username,password from activeuser order by isactive desc",
						null);
        activelist.moveToFirst();
        if(activelist.isAfterLast()){
        	activelist.close();
//        	onReg(null);
        }else{
        	username.setText(activelist.getString(0));
            password.setText(activelist.getString(1));
            activelist.close();
        }
        readdb.close();
        }
        
        
        
		
	}

	public void onReg(View view) {
		myDialog = ProgressDialog.show  
		    	(
		    		this,
		    		"初始设置",
		    		"正在下载数据，请稍候......"
		    	);
		
		new Thread() {
			public void run() {
				Looper.prepare();
		try {
			// ResponseHandler<String> responseHandler=new
			// BasicResponseHandler();
			// 发出HTTP request
			// getMethod.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			String uname = username.getText().toString();
			String pwd = password.getText().toString();
			String url = Convert.hosturl + "/UserRegister?UserName=" + uname
					+ "&UserPwd=" + pwd;
			HttpGet getMethod = new HttpGet(url);
			httpResponse = client.execute(getMethod);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				if ("1".equals(strResult)) {
					auh = DBhelper.getDBHelper(context);
					
					ContentValues activeuser = new ContentValues(4);
					Date now = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyyMMddHHmmss");

					String isactive = sdf.format(now);

					activeuser.put("isactive", isactive);
					activeuser.put("writepwd", "1");
					activeuser.put("username", uname);
					activeuser.put("password", pwd);
					
					synchronized (InfoSync.class) {
						SQLiteDatabase db = auh.getWritableDatabase();
						db.insert("activeuser", "username", activeuser);
						db.close();
					}
					
					
//					back(null);
					myDialog.dismiss();
					onLogin(null);
					
//					Message toMain = mMainHandler.obtainMessage();
//					toMain.obj="login";
//					mMainHandler.sendMessage(toMain);
//					onLogin(null);
				} else {
					myDialog.dismiss();
					Message toMain = mMainHandler.obtainMessage();
					toMain.obj="用户名已经存在。";
					mMainHandler.sendMessage(toMain);
//					setMsg();
//					Toast.makeText(context, "用户名已经存在！", 4000).show();
					return;
				}
			}
		} catch (Throwable t) {
			myDialog.dismiss();
//			setMsg("Request failed: " + t.toString());
			Message toMain = mMainHandler.obtainMessage();
			toMain.obj="网络不给力。";
			mMainHandler.sendMessage(toMain);
//			Toast.makeText(context, "Request failed: " + t.toString(), 4000)
//					.show();
		}finally{
			//auh.close();
		}
			}
		}.start();
	}
	
	public void setMsg(String m){
		msg.setText(m);
	}

	public void back(View view) {
		reg.setVisibility(View.GONE);
		username.setEnabled(true);
//		repd.setVisibility(View.GONE);
		loginform.setVisibility(View.VISIBLE);
		ckform.setVisibility(View.VISIBLE);
	}

	public void toReg(View view) {
		reg.setVisibility(View.VISIBLE);
		username.setEnabled(false);
//		repd.setVisibility(View.VISIBLE);
		ckform.setVisibility(View.GONE);
		loginform.setVisibility(View.GONE);
		myDialog = ProgressDialog.show  
		    	(
		    		this,
		    		"获取可用账户",
		    		"正在获取，请稍候......"
		    	);
		
		new Thread() {
			public void run() {
		try {
			// ResponseHandler<String> responseHandler=new
			// BasicResponseHandler();
			// 发出HTTP request
			// getMethod.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//			String uname = username.getText().toString();
//			String pwd = password.getText().toString();
			String url = Convert.hosturl + "/UserRegister";
			HttpGet getMethod = new HttpGet(url);
			httpResponse = client.execute(getMethod);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				if (!"2".equals(strResult)) {
					Message toMain = mMainHandler.obtainMessage();
					toMain.obj="reg"+strResult;
					mMainHandler.sendMessage(toMain);
				}
				myDialog.dismiss();
			}
		}catch (Throwable t) {
			myDialog.dismiss();
			Message toMain = mMainHandler.obtainMessage();
			toMain.obj="网络不给力。";
			mMainHandler.sendMessage(toMain);
		}finally{
		}
			}
		}.start();
	}

	public void onLogin(View view){
//    	new Handler().postDelayed(new Runnable() { 
//            public void run() { 
//                    Intent mainIntent = new Intent(TMain.this, Welcome.class);
//                    TMain.this.startActivity(mainIntent); 
//                    TMain.this.finish(); 
//                    overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//            } 
//    }, 3000);
		if(myDialog==null||!myDialog.isShowing()){
			myDialog = ProgressDialog.show  
	    	(
	    		this,
	    		"正在同步",
	    		"正在下载数据，请稍候......"
	    	);
		}
		
		
		new Thread() {
			public void run() {
		
    	uname=username.getText().toString();
    	String pwd=password.getText().toString();
    	String writepwd="1";
    	
    	String url=Convert.hosturl+"/UserLogin?UserName="+uname+"&UserPwd="+pwd;
    	HttpGet getMethod=new HttpGet(url);
    	SQLiteDatabase readdb=auh.getReadableDatabase();
    	SQLiteDatabase db=auh.getWritableDatabase();
    	try{
//    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
    		//发出HTTP request 
//    		getMethod.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); 
    		httpResponse=client.execute(getMethod);
    		if(httpResponse.getStatusLine().getStatusCode()==200){ 
                //取出回应字串 
                String strResult=EntityUtils.toString(httpResponse.getEntity()); 
                if("1".equals(strResult)){
                	auh=DBhelper.getDBHelper(context);
                	
                	String[] selectionArgs={uname,pwd};
                	int count=0;
                	synchronized (InfoSync.class) {
                	Cursor activelist=readdb.rawQuery("select * from activeuser where username=? and password=?", selectionArgs);
                	count=activelist.getCount();
                	activelist.close();
                	}
                	
                	ContentValues activeuser=new ContentValues(4);
                	Date now=new Date();
                	SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                	
                	String isactive=sdf.format(now);
                	
                	activeuser.put("writepwd", writepwd);
                	activeuser.put("isactive",isactive);
                	if(count==0){
                		activeuser.put("username", uname);
                		activeuser.put("password", pwd);
                		synchronized (InfoSync.class) {
                			db.insert("activeuser", "username", activeuser);
                		}
//                		activelist.requery();
//                		activelist.getCount();
                		
                	}else{
                		synchronized (InfoSync.class) {
                			db.update("activeuser", activeuser, "username=? and password=?", selectionArgs);
                		}
//                		activelist.requery();
//                		activelist.getCount();
                	}
                	if(!uname.equals(Convert.uname)){
                		Convert.uname=uname;
                		synchronized (Convert.class) {
        					Convert.syncList.clear();
        				}
                	}
                	
    	            Convert.upwd=pwd;
                	String[] codearr={uname};
                	synchronized (InfoSync.class) {
                	Cursor contentlist = readdb.rawQuery("select code,title,content,type,replyType from content where level='1' and username=? ",codearr);
            		count=contentlist.getCount();
            		contentlist.close();
                	}
            		UserUtil.getUser(context);
        			//readdb.close();
        			//db.close();
        			
        			
            		if(count==0){
    					UrlSync urlSync=new UrlSync();
    					urlSync.setUri(Convert.hosturl+"/InfoAll");
    					urlSync.setNotice(false);
    					urlSync.setSyncType(UrlSync.INFOALL);
    					urlSync.setMaincode("main");
//    					Convert.syncList.add(urlSync);
            			getMethod=new HttpGet(urlSync.getAllUri());
            			httpResponse=client.execute(getMethod);
                		if(httpResponse.getStatusLine().getStatusCode()==200){ 
                            //取出回应字串 
                            String urlResult=EntityUtils.toString(httpResponse.getEntity()); 
                            InfoSync infoSync = new InfoSync();
                            infoSync.savecontnet(urlResult, auh, urlSync);
                            String[] codearr1={uname};
        					SQLiteDatabase re=auh.getReadableDatabase();
        					int count1=0;
        					synchronized (InfoSync.class) {
                        	Cursor contentlist1 = re.rawQuery("select code,title,content,type,replyType from content where level='1' and username=? ",codearr1);
                    		count1=contentlist1.getCount();
                    		contentlist1.close();
        					}
                			//re.close();
        					myDialog.dismiss();
                			if(count1>0){
                    			goWelcome();
                    			
                			}
                		}else{
                			myDialog.dismiss();
                    		Message toMain = mMainHandler.obtainMessage();
                			toMain.obj="同步失败。";
                			mMainHandler.sendMessage(toMain);
                		}
            		}else{
            			myDialog.dismiss();
            			goWelcome();
            		}
            		


//                	Intent intent = new Intent();
//                	intent.setClass(TMain.this, Welcome.class);
//                	startActivity(intent);
//                	finish();
//                	overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

                }else{
                	myDialog.dismiss();
                	Message toMain = mMainHandler.obtainMessage();
        			toMain.obj="用户名或者密码错误。";
        			mMainHandler.sendMessage(toMain);
//                	Toast.makeText(this, "用户名或者密码错误！", 2000).show();
                }
//                Toast.makeText(this, "Request Success: "+strResult, 4000).show();
            }else{ 
            	myDialog.dismiss();
            	Message toMain = mMainHandler.obtainMessage();
    			toMain.obj="网络不给力。";
    			mMainHandler.sendMessage(toMain);
//            	Toast.makeText(this, "Request failed status: "+httpResponse.getStatusLine().getStatusCode(), 4000).show();
            } 
    		
    	}catch(Throwable t){
    		myDialog.dismiss();
    		Message toMain = mMainHandler.obtainMessage();
			toMain.obj="网络不给力。";
			mMainHandler.sendMessage(toMain);
//    		Toast.makeText(this, "Request failed: "+t.toString(), 4000).show();
    	}finally{
			//auh.close();
    		readdb.close();
    		db.close();
		}
		}
		
	}.start();
    	
    }
	public void goWelcome(){
		Intent mainIntent = new Intent(TMain.this, Welcome.class);
        TMain.this.startActivity(mainIntent); 
        TMain.this.finish(); 
	}
	public void onDestroy() {
		super.onDestroy();
//	    mChildHandler.getLooper().quit();
	}
	public void reSet(View view) {

	}
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
}